/**
 * 
 */
package com.vector.ding.commons.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.vector.ding.exception.BaseException;

/**
 * @author vector
 *
 */
public final class BeanUtil {

	// no way to instance
	private BeanUtil() {
		
	}
	
	/**
	 * get java bean property map
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> getPropertyMap(Object bean) {
		Map<String, Object> proMap = new HashMap<String, Object>();
		Field[] fields = bean.getClass().getDeclaredFields();
		if (fields == null || fields.length == 0)
			return proMap;
		
		try {
			for (Field field: fields) {
				field.setAccessible(true);
				proMap.put(field.getName(), field.get(bean));
			}
		} catch (SecurityException e) {
			throw new BaseException(e);
		} catch (IllegalArgumentException e) {
			throw new BaseException(e);
		} catch (IllegalAccessException e) {
			throw new BaseException(e);
		}
		
		return proMap;
	}
	
	/**
	 * @param propertyMap
	 * @param bean
	 */
	public static <T> void fillBeanProperty(Map<String, Object> propertyMap, T bean, Set<String> excludeProSet) {
		Field[] fields = bean.getClass().getDeclaredFields();
		if (fields == null || fields.length == 0)
			return;
		
		try {
			for (Field field: fields) {
				if (null != excludeProSet && excludeProSet.contains(field.getName()))
					continue;
				field.setAccessible(true);
				field.set(bean, propertyMap.get(field.getName()));
			}
		} catch (SecurityException e) {
			e.printStackTrace();
			throw new BaseException(e);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			throw new BaseException(e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new BaseException(e);
		}
	}
	
	public static <T> Set<String> getPropertySet(Class<? extends T> type) {
		Set<String> set = new HashSet<String>();
		Field[] fields = type.getDeclaredFields();
		if (fields == null || fields.length == 0)
			return set;
		
		try {
			for (Field field: fields) {
				if (field.getClass() != type)
					continue;
				set.add(field.getName());
			}
		} catch (SecurityException e) {
			e.printStackTrace();
			throw new BaseException(e);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			throw new BaseException(e);
		} 
		
		return set;
	}
}
